package com.cnr.util;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.cnr.model.Credentials;
import com.cnr.model.Posts;

public class ManagePosts {

	private static final Logger logger = Logger.getLogger(ManagePosts.class);

	@SuppressWarnings("unchecked")
	public List<Posts> getPosts() {
		Session session = HibernateUtil.getSession();
		List<Posts> posts = null;
		try {
			posts = (List<Posts>) session.createQuery("FROM Posts").list();
		} catch (HibernateException e) {
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
		if(posts == null || posts.isEmpty()){
			logger.info("No posts found in Posts storage!");
		}
		return posts;
	}

	@SuppressWarnings("unchecked")
	public List<Posts> getPostsOfUser(Credentials user) {
		Session session = HibernateUtil.getSession();
		List<Posts> posts = null;
		try {
			posts = session
					.createCriteria(Posts.class)
					.add(Restrictions.and(Restrictions.eq("credentials",
							user))).list();
		} catch (HibernateException e) {
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
		if(posts == null || posts.isEmpty()){
			logger.info("No posts found for user " + user);
		}
		return posts;
	}

	public Long addPost(String link, String via, Credentials user) {
		Session session = HibernateUtil.getSession();
		Long postId = null;
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Posts post = new Posts();
			post.setLink(link);
			post.setVia(via);
			post.setCredentials(user);
			postId = (Long) session.save(post);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
		return postId;
	}

	public void updatePost(Long postID, String link, String via, Credentials user) {
		Session session = HibernateUtil.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Posts post = (Posts) session.get(Posts.class, postID);
			post.setLink(link);
			post.setVia(via);
			post.setCredentials(user);
			session.update(post);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
	}

	public void deletePost(Long postID) {
		Session session = HibernateUtil.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Posts post = (Posts) session.get(Posts.class, postID);
			session.delete(post);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
	}

}
